package com.innovativethinking.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.innovativethinking.domain.BufferName;
import com.innovativethinking.domain.KanbanTweet;
import com.innovativethinking.domain.service.KanbanTweetService;
import com.innovativethinking.web.name.RequestAttributeName;

@SuppressWarnings("serial")
@Singleton
public class BufferSizeServlet extends HttpServlet {
	
	@Inject private UserService userService = null;
	@Inject private KanbanTweetService ktService = null;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		User user = userService.getCurrentUser();
		
		String buffer = getBuffer(req);
		
		List<KanbanTweet> tweets = ktService.getMyTweetsByBuffer(buffer, user);
		
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.println("(" + tweets.size() + ")");
		out.close();
	}
	
	private String getBuffer(HttpServletRequest req) {
		
		if (req.getQueryString() != null && !req.getQueryString().startsWith(RequestAttributeName.KANBAN_ID)) {
			return req.getParameter(RequestAttributeName.BUFFER);
		}
		
		String buffer = (String) req.getAttribute(RequestAttributeName.BUFFER);
		
		if (buffer != null) return buffer;
		
		return BufferName.INPUTQUEUE;
	}
}
